package com.xzy.spring.demo.proxy.auto.jdk;

import com.xzy.spring.demo.proxy.RealSubject;
import com.xzy.spring.demo.proxy.Subject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author xzy
 * @date 2021/3/11 21:40
 * 说明：JDK动态代理
 */
public class ProxyFactory {

    // 目标对象
    private final Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    // 动态生成代理对象
    public Object getProxyInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 附加的代理逻辑
                System.out.println(">>>开始执行");

                // 目标方法
                method.invoke(target, args);

                // 附加的代理逻辑
                System.out.println(">>>执行结束");
                return null;
            }
        });
    }

    public static void main(String[] args) {
        Subject realSubject = new RealSubject();
        realSubject.request();
        System.out.println(realSubject.getClass());

        System.out.println("");

        Subject proxySubject = (Subject) new ProxyFactory(realSubject).getProxyInstance();
        proxySubject.request();
        System.out.println(proxySubject.getClass());
    }
}
